package com.cn.hnust.controller;

import java.io.IOException;
import java.io.Writer;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cn.hnust.pojo.Lfdcomment;
import com.cn.hnust.pojo.Lfdlifashi;
import com.cn.hnust.service.ILfdcommentService;
import com.cn.hnust.service.ILfdlifashiService;
import com.google.gson.Gson;

@Controller
@RequestMapping("/Lfdlifashi")
public class LfdlifashiController {

	@Resource
	private ILfdlifashiService LfdlifashiService;

	@Resource
	private ILfdcommentService LfdcommentService;

	@RequestMapping("/selectLfdlifashiBySid")
	public void selectLfdlifashiBySid(HttpServletResponse response, Lfdlifashi Lfdlifashi, Integer sid)
			throws IOException {
		List<Lfdlifashi> list = LfdlifashiService.selectLfdlifashiBySid(sid);
		Gson gson = new Gson();
		String json = gson.toJson(list);
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "GET,POST");
		response.setContentType("text/json,charset=utf-8");
		response.setCharacterEncoding("utf-8");
		Writer out = response.getWriter();
		out.write(json);
		out.flush();
	}

	@RequestMapping("/selectLfdlifashiById")
	public void selectLfdlifashiById(HttpServletResponse response, Lfdlifashi Lfdlifashi, Integer id)
			throws IOException {
		Lfdlifashi = LfdlifashiService.selectByPrimaryKey(id);
		Gson gson = new Gson();
		String json = gson.toJson(Lfdlifashi);
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "GET,POST");
		response.setContentType("text/json,charset=utf-8");
		response.setCharacterEncoding("utf-8");
		Writer out = response.getWriter();
		out.write(json);
		out.flush();
	}

	@RequestMapping("/updateLfdlifashiById")
	public void updateLfdlifashiById(HttpServletResponse response, Lfdlifashi Lfdlifashi,Lfdlifashi Lfd, Integer id,Integer lid,Double pinfen)
			throws IOException {
		List<Lfdcomment> list = LfdcommentService.selectLfdcommentByLid(lid);
		
		for(int i=0;i<list.size();i++) {
			pinfen=pinfen+list.get(i).getPinfen();
		}
		Lfdlifashi = LfdlifashiService.selectByPrimaryKey(lid);
		Lfd.setId(lid);
		Lfd.setPinfen(pinfen/list.size()+"");
		LfdlifashiService.updateByPrimaryKeySelective(Lfd);
		Gson gson = new Gson();
		String json = gson.toJson(Lfdlifashi);
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "GET,POST");
		response.setContentType("text/json,charset=utf-8");
		response.setCharacterEncoding("utf-8");
		Writer out = response.getWriter();
		out.write(json);
		out.flush();
	}

}
